import * as Cesium from 'cesium';
import gisTools from '../GisTools';
import mouseHelper from '../MouseHelper';
//当前类使用的全局的viewer
let cviewer: any = {};
//当前类的事件句柄
let handler: any = {};

/**
 * 添加、清除、连续添加测试过
 */
class DrawPolyline {
  _drawingGraphic: any;
  _drawingPositions: any;
  _drawingPointEntities:any;
  isDrawingEnd: any;
  drawedPositions: any;
  drawedGraphics: any;
  constructor(viewer: any) {
    //绘制中的graphic-主要绘制线   --- 脏数据
    this._drawingGraphic = null;
    //绘制中的geometry-主要绘制线  -数据类型 Cartesian3  ---脏数据
    this._drawingPositions = [];
    //绘制过程中活动的点 --脏数据
    this._drawingPointEntities=[];
    //绘制完成的graphics 数组 Array<any>
    this.drawedGraphics = [];
    //绘制完成的geometry  -数据类型 Array<Cartesian3>
    this.drawedPositions = [];
    //是否绘制结束
    this.isDrawingEnd = false;
    cviewer = viewer;
    handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  }

  /**
   * 开始绘制
   * @param bNeed  true | false  表示绘制动作是否是连续性的，即绘制完一个不结束，默认false
   * @param options  {
   *   "Polyline":{ "stroken":"线颜色","width":"线宽度" }
   *      "popOffset":{x:400,y:0}
   * }
   */
  startDraw(bNeed: boolean=false, options: any={}) {
    this.clearDrawGraphic();
    let _this = this;
    let { popOffset } = options;
    //创建初始化
    mouseHelper.createHelper({ x:-500,y:-500 }, '',popOffset);
    //左键事件-添加真实的点
    handler.setInputAction(function(evt: any) {
      let car3 = gisTools.getCar3Position(cviewer,evt.position);
      if(car3){
        if(_this._drawingPositions.length===0){
          _this._drawingPositions.push(car3.clone());
        }
        _this._drawingPositions.push(car3);
        _this.createPoint(car3.clone());
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    //鼠标移动事件-添加虚拟的点
    handler.setInputAction(function(evt: any) {
      let car3 = gisTools.getCar3Position(cviewer,evt.endPosition);
      //未点击左键的时候的提示
       if(_this._drawingPositions.length===0){
         mouseHelper.updateHelper(evt.endPosition, '左键点击开始',popOffset);
       }
        //线最少两个点-一个点的时候提示
        if (_this._drawingPositions.length > 0  && _this._drawingPositions.length < 2  ) {
          mouseHelper.updateHelper(evt.endPosition, '左键点击继续绘制',popOffset);
        }
        //线的点数大于等于2的时候的提示
        if (_this._drawingPositions.length >= 2) {
          mouseHelper.updateHelper(evt.endPosition, '左键点击继续绘制，右键点击结束绘制',popOffset);
        }
        //点的数量大于等于1的时候开始画线
        if(_this._drawingPositions.length>0){
          _this._drawingPositions.pop();
          _this._drawingPositions.push(car3);
          if (!_this._drawingGraphic) {
            let { Polyline } = options;
            _this._drawingGraphic = _this.createPolyline(Polyline);
          }
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    //鼠标右键事件
    handler.setInputAction(function(evt: any) {
      let car3 = gisTools.getCar3Position(cviewer,evt.position);
      if(_this._drawingPositions.length>1){
        _this.rightHandler(_this,car3,bNeed)
      }
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }

  rightHandler(_this:any,car3:any,flag:boolean){
    //鼠标动态绘制过程的点+1
    _this._drawingPositions.push(car3);
    _this.createPoint(car3.clone());
    let graphic:any=null;
    graphic=_this.createHasPolyline(_this._drawingPositions)
    console.log(graphic);
    //某个图形绘制结束的的存储
    _this.drawedGraphics.push(graphic);
    //当前图形绘制完的存储
    _this.drawedPositions.push(JSON.parse(JSON.stringify(_this._drawingPositions)));
    //延迟还原要不会有闪动的效果
     setTimeout(()=>{
       //动态图形的还原
       _this._drawingGraphic = null;
       _this._drawingPositions = [];
     },500)
    //如果是一次绘制，绘制结束完，清除事件
    if(!flag){
      _this.isDrawingEnd = true;
      _this.endDrawing();
    }
  }
  /**
   *结束绘制的事件
   */
  endDrawing() {
    if(handler){
      handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    mouseHelper.removeHelper();
    return true;
  }

  /**
   * 清除绘制的Graphic
   */
  clearDrawGraphic() {
    this.endDrawing();
    if(this.drawedGraphics.length>0){
      this.drawedGraphics.forEach((item:any)=>{
        cviewer.entities.remove(item)
      })
    }
    if(this._drawingPointEntities.length>0){
      this._drawingPointEntities.forEach((item:any)=>{
        cviewer.entities.remove(item)
      })
    }
    this.isDrawingEnd=false;
    this._drawingGraphic = null;
    this._drawingPositions = [];
    this.drawedPositions=[];
    this.drawedGraphics=[];
    return true;
  }

  createPoint(cartesian:any) {
    var $this = this;
    var point = cviewer.entities.add({
      position: cartesian,
      point: {
        pixelSize: 10,
        color: Cesium.Color.YELLOW,
      }
    });
    $this._drawingPointEntities.push(point);
    return point;
  }



  /**
   * 创建线
   * @param positionArr-绘制过程中的动态的线
   * @param style
   */
  createPolyline(style: any) {
    if(!style){
      style={
        stroken:"#DC143C",
        width:3
      }
    }
    style['stroken'] = style?.stroken ?? '#DC143C';
    style['width'] = style?.width ?? 3;
    let _this = this;
    var polyline = cviewer.entities.add({
      polyline: {
        id: 'area_search_draw_graphic_polyline' + new Date().getTime(),
        //使用cesium的peoperty
        positions: new Cesium.CallbackProperty(function() {
          return _this._drawingPositions;
        }, false),
        show: true,
        material: Cesium.Color.fromCssColorString(style['stroken']),
        width: style['width'],
        clampToGround: true,
      },
    });
    return polyline;
  }


  /**
   * 添加折线-一次绘制动作结束需要添加的，针对连续的线设置的
   * @param carArr
   */
  createHasPolyline(carArr:any) {
    let newCarArr:any=[];
    //避免数据改变（_drawingPositions）的影响
    carArr.forEach((item:any)=>{
      newCarArr.push(item.clone());
    })
    let style={
      stroken:"#DC143C",
      width:3
    }
    var polyline = cviewer.entities.add({
      polyline: {
        positions: newCarArr,
        show: true,
        material: Cesium.Color.fromCssColorString(style['stroken']),
        width: style['width'],
        clampToGround: true,
      },
    });
    return polyline;
}

}

export default DrawPolyline;



